// import Agreement from '@/static/js/Agreement.js'
//var agreementJs = require('@/static/js/Agreement.js')
const ble = uni.requireNativePlugin('sand-plugin-bluetooth');
class YBKC_Sanhe_5101_HID {
	constructor() {
		//初始化监听
		this.DeviceObj.initListener();
	}
	Link(connectId, callBackDeviceList, callBackLinkSuccess) { // 连接
		if (!connectId) {
			//提供一个蓝牙选择列表，让用户选择其中一个蓝牙设备
			this.DeviceObj.startScan(callBackDeviceList);
		} else {
			this.DeviceObj.toConnect(connectId, callBackLinkSuccess);
		}
	}
	StopFind() { // 停止搜索
		this.DeviceObj.stopScan()
	}
	//获取状态，通过监听实时返回设备当前的状态
	//1、回调参数当前设备的状态
	GetStatus(callBackGetStatus) {
		this.DeviceObj.callBackGetStatus = callBackGetStatus;
	}
	//停止设备连接，中断设备连接
	Disconnect(deviceId) { // 断开
		// console.log(deviceId)
		this.DeviceObj.disConnect(deviceId);
	}
	//获取数据的回调函数
	//回调实际返回的真实值
	CallBackGetData(callBackData) { // 返回获取的数据
		this.DeviceObj.callBackData = callBackData;
	}
	//写入函数，暂时保留
	WriteData() { // 写入数据
	}

	//游标卡尺蓝牙对象
	DeviceObj = {
		callBackDeviceList: null,
		callBackData: null,
		callBackGetStatus: null,
		curDeviceId: '',
		initListener() {
			var that = this;
			//适配器监听
			ble.onBluetoothAdapterStateChange({}, (res) => {
				// console.log('适配器状态变化', res);
				// // that.msg = res.message;
				// that.addLog(res.message);
			});
			//发现设备监听
			ble.onBluetoothDeviceFound({}, (res) => {
				// console.log('发现了设备', JSON.parse(res.devices));
				if (res.status == '2500') {
					let devices = JSON.parse(res.devices);
					//that.addFindDevice(devices);
					if (typeof(that.callBackDeviceList) == "function") {
						that.callBackDeviceList(devices);
					}
				}
			});
			//监听设备连接监听
			ble.onBLEConnectionStateChange({}, (res) => {
				// console.log(res)
				let deviceId = res.deviceId;
				let connected = res.connected;
				// let list = [...that.BluetoothDeviceList];
				// let dev = list[that.deviceMap[deviceId]];
				// dev.connected = connected;
				// that.BluetoothDeviceList = list;
				// that.addLog(dev.name + "连接状态=" + connected);
				// console.log(dev.name + "连接状态=" + connected);
				// //连接成功，获取服务和订阅特征
				if (that.curDeviceId == deviceId && connected == true) {
					that.notify(deviceId);
				}
				// console.log(connected);
				if (typeof(that.callBackGetStatus) == "function") {
					if (that.curDeviceId == deviceId) {
						that.callBackGetStatus(deviceId, connected);
					}
				}
			});
			//监听特征数据
			ble.onBLECharacteristicValueChange({}, (res) => {
				console.log(3333) 
			    console.log(JSON.stringify(res))
				// that.addLog('十六进制值:' + res.value); // 点击按钮，给聚焦的表格输入框赋值
				// console.log('十六进制值:' + res.value);
				
				let value = res.value;
				//that.addLog('解析后的值:' + JSON.stringify(that.hex2Bytes(value)));
				var originValue = that.hex2Bytes(value);
				console.log(originValue);
				//三和的游标卡尺，8个数组，倒数，5，6数组是值
				// that.addLog('解析后的实际值:' + (parseInt(parseInt(originValue[5]) * 256) + parseInt(originValue[
				// 	6])));

				if (typeof(that.callBackData) == "function") {
					// 拿到的值为测量值的100倍，且数值格式不是直接测量的数值 ，所以 先转译 再做一下处理
					let obj = {
						Nums: (parseInt(parseInt(originValue[5]) * 256) + parseInt(originValue[6])) /
							100,
						Model: res
					}
					that.callBackData(obj);
				}


				// uni.$emit('GetNums', {
				// 	Num: (parseInt(parseInt(originValue[5]) * 256) + parseInt(originValue[6]))
				// })

				// direction.next()
				//console.log('解析后的值:' + JSON.stringify(that.hex2Bytes(value)));
			});
			//打开适配器
			ble.openBluetoothAdapter({}, (res) => {
				// console.log(res);
				// // that.msg = res.message;
				// that.addLog(res.message);
				// // that.startScan()
			});
		},
		//启动扫描
		startScan(callBackDeviceList) {
			var that = this;
			//var that = this
			// console.log(callBackDeviceList)
			that.callBackDeviceList = callBackDeviceList;
			ble.startBluetoothDevicesDiscovery({}, (res) => {});
		},
		//停止扫描
		stopScan() {
			ble.stopBluetoothDevicesDiscovery({}, (res) => {});
		},
		//连接设备
		toConnect(deviceId, callBackLinkSuccess) {
			var that = this;
			//停止扫描
			ble.stopBluetoothDevicesDiscovery({}, (res) => {
				//that.addLog(res.message);
			});
			//开始连接
			// console.log(1)
			that.curDeviceId = deviceId;
			ble.createBLEConnection({
				deviceId: deviceId
			}, (res) => {
				if (typeof(callBackLinkSuccess) == "function") {
					callBackLinkSuccess(res);
				}
				
				// setInterval(()=>{
				// 	ble.readBLECharacteristicValue({
				// 		deviceId: deviceId,
				// 		serviceId: '00001812-0000-1000-8000-00805f9b34fb',
				// 		characteristicId: '00002a4d-0000-1000-8000-00805f9b34fb'
				// 	}, (res3) => {
				// 		console.log('res4'+ JSON.stringify(res3));
				// 	});
				// },2000);
				
				//that.addLog(res.message);
				// //加入自动重连
				// ble.addAutoReconnect({
				// 	deviceId: deviceId
				// }, (res2) => {
				// 	console.log(1)
				// 	that.addLog(res2.message);
				// });
			});
		},
		//断开连接
		disConnect(deviceId) {
			var that = this;
			if (deviceId) {
				//var that = this
				ble.removeAutoReconnect({
					deviceId: deviceId
				}, (res) => {
					//that.addLog(res.message);
					ble.closeBLEConnection({
						deviceId: deviceId
					}, (res2) => {
						//that.addLog(res2.message);
					});
				});
			}
			/* if (that.curDeviceId) {
				//var that = this
				ble.removeAutoReconnect({
					deviceId: that.curDeviceId
				}, (res) => {
					//that.addLog(res.message);
					ble.closeBLEConnection({
						deviceId: that.curDeviceId
					}, (res2) => {
						//that.addLog(res2.message);
					});
				});
			} */
		},
		//刷新服务和订阅特征
		notify(deviceId) {
			//var that = this
			let timeout = 0;
			setTimeout(() => {
				//获取服务列表
				ble.getBLEDeviceServices({
					deviceId: deviceId
				}, (res) => {
					console.log(res);
					if (res.status == '2500') {
						let services = JSON.parse(res.services);
						//that.addLog(res.message + "," + res.services);
						//由于是异步方法，采用递归进行遍历
						var diguiServices = function(serArr, index) {
							ble.getBLEDeviceCharacteristics({
								deviceId: deviceId,
								serviceId: serArr[index].uuid
							}, (res2) => {
								// that.addLog(res2.message + "," + res2.characteristics);
								console.log(res2.message + "," + res2.characteristics);
								let characteristics = JSON.parse(res2.characteristics);
								//订阅设备特征
								//if(true)//(serArr[index].uuid.indexOf('1905') >= 0) {
								for (let j = 0; j < characteristics.length; j++) {
									let characteristic = characteristics[j];
									console.log('3333444')
									//if (characteristic.properties.notify == true) {
										ble.notifyBLECharacteristicValueChange({
											deviceId: deviceId,
											serviceId: serArr[index].uuid,
											characteristicId: characteristic
												.uuid
										}, (res3) => {
											console.log('res3+'+JSON.stringify(res3));
											//that.addLog(res3.message);
										});
									//}
									//读特征值
									if (characteristic.properties.read == true) {
										console.log('读数据：'+ deviceId +',serviceId:'+ serArr[index].uuid +',characteristicId'+ characteristic.uuid )
										ble.readBLECharacteristicValue({
											deviceId: deviceId,
											serviceId: serArr[index].uuid,
											characteristicId: characteristic
												.uuid
										}, (res3) => {
											//that.addLog('res4'+ JSON.stringify(res3));
										});
									}
									//写一个值过去
									if (characteristic.properties.write == true) {
										ble.writeBLECharacteristicValue({
											deviceId: deviceId,
											serviceId: serArr[index].uuid,
											characteristicId: characteristic
												.uuid,
											value: "01" //十六进制数据
										}, (res3) => {
											//that.addLog(res3.message);
										});
									}
								}
								//}


								let index2 = index + 1;
								if (index2 >= serArr.length) {
									return;
								} else {
									// console.log("递归下一个服务的特征值");
									diguiServices(serArr, index2);
								}
							});
						};
						//开始遍历服务
						diguiServices(services, 0);
					} else {
						//that.addLog(res.message);
					}
				});
			}, timeout);
		},
		// getAllScan() {
		// 	var that = this
		// 	//获取已经扫描到的所有设备
		// 	ble.getBluetoothDevices({}, (res) => {
		// 		that.addLog('获取所有:' + res.devices);
		// 		let arr = JSON.parse(res.devices);
		// 		that.addFindDevice(arr);
		// 		for (let i = 0; i < arr.length; i++) {
		// 			let dev = arr[i];
		// 			if (dev.restore) {
		// 				that.addLog('准备恢复这台设备' + dev.name);
		// 				that.toConnect(dev.deviceId);
		// 			}
		// 		}
		// 	});
		// },
		// getConnected() {
		// 	var that = this
		// 	//获取已连接的所有设备
		// 	ble.getConnectedBluetoothDevices({}, (res) => {
		// 		that.addLog('获取已连:' + res.devices);
		// 	});
		// },
		// getStatus() {
		// 	var that = this
		// 	//获取当前适配器状态
		// 	ble.getBluetoothAdapterState({}, (res) => {
		// 		that.addLog('获取状态:' + JSON.stringify(res));
		// 	});
		// },
		// addLog(msg) {
		// 	var that = this
		// 	that.log = that.log + new Date().toLocaleString() + ":" + msg + "\r\n";
		// 	that.toBottom = '';
		// 	setTimeout(() => {
		// 		that.toBottom = "bottomId";
		// 	}, 200);
		// },
		// addFindDevice(devices) {
		// 	var that = this
		// 	let list = [...that.BluetoothDeviceList];
		// 	for (let i = 0; i < devices.length; i++) {
		// 		let dev = devices[i];
		// 		//去重
		// 		if (that.deviceMap[dev.deviceId] >= 0) {
		// 			let index = that.deviceMap[dev.deviceId];
		// 			//更新
		// 			list.splice(index, 1, dev);
		// 		} else {
		// 			//新增
		// 			list.push(dev);
		// 			that.deviceMap[dev.deviceId] = list.length - 1;
		// 		}
		// 	}
		// 	that.BluetoothDeviceList = list;
		// },
		// readData() {
		// 	var that = this
		// 	ble.readBLECharacteristicValue({
		// 		deviceId: 'DDCC-EE-AA-BB-CC',
		// 		serviceId: '0000-1902-C503',
		// 		characteristicId: '0000-1902-C503-0001'
		// 	}, (res) => {
		// 		if (res.status == '2500') {
		// 			//读取API调用成功,请在onBLECharacteristicValueChange获取特征值数据
		// 		}
		// 	});
		// },
		//十六进制字符串转数组
		hex2Bytes(hexStr) {
			var that = this
			var pos = 0;
			var len = hexStr.length;
			if (len % 2 != 0) {
				return null;
			}
			len /= 2;
			var hexA = new Array();
			for (var i = 0; i < len; i++) {
				var s = hexStr.substr(pos, 2);
				var v = parseInt(s, 16);
				hexA.push(v);
				pos += 2;
			}
			return hexA;
		},
	}



}






// var connectId = "";

// function Link(connectId, callBackDeviceList, callBackLinkSuccess) {

// 	DeviceObj.initListener()
// 	if (!connectId) {
// 		//提供一个蓝牙选择列表，让用户选择其中一个蓝牙设备
// 		DeviceObj.startScan(callBackDeviceList);
// 	} else {
// 		DeviceObj.toConnect(connectId, callBackLinkSuccess);
// 	}
// }

// function CallBackGetData(callBackData) { // 返回获取的数据
// 	DeviceObj.callBackData = callBackData;
// }

// var SonAgreement = {
// 	// constructor(ID) {
// 	// 	super()
// 	// } 
// 	Link: function(connectId, callBackDeviceList, callBackLinkSuccess) {

// 		DeviceObj.initListener()
// 		if (!connectId) {
// 			//提供一个蓝牙选择列表，让用户选择其中一个蓝牙设备
// 			DeviceObj.startScan(callBackDeviceList);
// 		} else {
// 			DeviceObj.toConnect(connectId, callBackLinkSuccess);
// 		}
// 	},
// 	CallBackGetData: function(callBackData) { // 返回获取的数据
// 		DeviceObj.callBackData = callBackData;
// 	},
// 	stopScan: function() { // 断开
// 		DeviceObj.stopScan()
// 	}
// }

// module.exports = SonAgreement
export default QFC_GUANGLU_IP65